package com.gzz.redis.cachedata;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author higmd
 */
@Component
public class RedisToolUtil {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置指定 key 的值
     *
     * @param key     键
     * @param value   值
     * @param seconds 时间(秒) seconds要大于0 如果seconds小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, Object value, long seconds) {
        try {
            if (seconds == 0) {
                redisTemplate.opsForValue().set(key, value);
            } else {
                redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置指定 key 的值
     *
     * @param key     键
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 模糊匹配批量删除
     *
     * @param pattern 匹配的前缀
     */
    public void deleteByPattern(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }
}
